import 'dart:convert';

import 'package:im_app/im/util/MapUtil.dart';
import 'package:logger/logger.dart';
import 'package:sqflite/sqflite.dart';

import '../pojo/ImPojo.dart';
import '../util/DateUtil.dart';
import '../util/ImSingleton.dart';
import 'BaseDao.dart';

class ImConfigDao extends BaseDao {

  var _logger = Logger(
    printer: PrettyPrinter(),
  );

  Future<ImConfig?> getByName(String name) async {
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    List? list = await database?.rawQuery("select * from im_config where word = ? limit 1", [name]);
    if (list != null && list.length > 0) {
      return Future.value(_toImConfig(list[0]));
    }
    return Future.value(null);
  }

  Future<List<ImConfig>> getByNames(List<String> names) async {
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;

    String param = names.map((p)=> '?').join(",");
    List<dynamic> params = [];
    params.addAll(names);

    List? list = await database?.rawQuery("select * from im_config where name in (${param})", params);
    return list != null ? Future.value(list.map((map)=>_toImConfig(map)).toList()) : Future.value([]);
  }

  Future<List<ImConfig>> getAll() async {
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    String sql = "select * from im_config where status = 1";
    List<Map<String, dynamic?>>? list = await database?.rawQuery(sql);
    return list != null ? Future.value(list.map((map)=>_toImConfig(map)).toList()) : Future.value([]);
  }

  Future<void> batchInserts(List<ImConfig> imConfigs) async {
    if (imConfigs.isEmpty) return;
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    for (var imConfig in imConfigs) {
      var data = _toInsertValueMap(imConfig);
      int? id = await database?.insert("im_config", data);
      imConfig.id = id;
    }
  }

  Future<void> batchUpdates(List<ImConfig> imConfigs) async {
    if (imConfigs.length < 1) return;
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    Batch? batch = database?.batch();
    for (var imConfig in imConfigs) {
      var data = _toInsertValueMap(imConfig);
      batch?.update("im_config", data, where: "name = ?", whereArgs:[imConfig.name]);
    }
    List<Object?>? list = await batch?.commit();
    _logger.i("batch json: " + jsonEncode(list));
  }

  Map<String, dynamic?> _toInsertValueMap(ImConfig imConfig) {
    Map<String, dynamic?> map = {};
    map['name'] = imConfig.name;
    map['currentUserId'] = imConfig.currentUserId;
    map['content'] = imConfig.content;
    map["status"]= imConfig.status?.value;
    map['createTime'] = DateUtil.formatDate(imConfig.createTime);
    map['updateTime'] = DateUtil.formatDate(imConfig.updateTime);
    return map;
  }

  ImConfig _toImConfig(Map<String, dynamic> map) {
    var config = ImConfig(name: MapUtil.getString(map, "name"),
        content: MapUtil.getString(map, "content"),
        currentUserId: MapUtil.getString(map, "currentUserId"),
        status: ImConfigStatus.ofValue(MapUtil.getInt(map, "status")),
    );
    config.id = MapUtil.getInt(map, "id");
    config.createTime = MapUtil.getDate(map, "createTime");
    config.updateTime = MapUtil.getDate(map, "updateTime");
    return config;
  }
}